package com.vandytrack.android.servlet;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.google.gson.*;

public class UploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/*
	 * When we get the HttpRequest from the phone, get our object and then
	 * upload it to the database. 
	 * 
	 * Because of the way Google App Engine has set up their datastore, the 
	 * object needs to be uploaded twice (as two separate objects). This is
	 * done for a few reasons.
	 * 
	 * When a browser queries the server for new location data,
	 * we want to poll for the latest data and not worry about the rest.
	 * For this reason, having a small index of objects used only for updating
	 * the web map would be much easier than trying to change some parameter 
	 * consistent with all objects.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		
		String serializedParams = "";
		serializedParams = req.getParameter("serializedObj");

		if (serializedParams != null) {
			Gson gson = new Gson();
			VanLocation vanLocation = gson.fromJson(serializedParams, VanLocation.class);
			
			resp.getWriter().println(gson.toJson(vanLocation));
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				pm.makePersistent(vanLocation);
			} finally {
				pm.close();
			}
		}
	}
}
